package com.example.liliang.rediogrouptest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private RadioGroup rb_sex;
    private RadioButton rb_male, rb_female;
    private RadioButtonListener radioButtonListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rb_sex = findViewById(R.id.rb_sex);
        rb_male = findViewById(R.id.rb_male);
        rb_female = findViewById(R.id.rb_female);
        radioButtonListener = new RadioButtonListener();
        // 绑定监听器
        rb_sex.setOnCheckedChangeListener(radioButtonListener);
    }

    /**
     * 选择监听器
     */
    class RadioButtonListener implements RadioGroup.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.rb_male:
                    Toast.makeText(MainActivity.this, rb_male.getText().toString(), Toast.LENGTH_SHORT).show();
                    break;
                case R.id.rb_female:
                    Toast.makeText(MainActivity.this, rb_female.getText().toString(), Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    }
}
